<!-- 加工配送 -->
<template>
  <div class="mod-config">
      <el-tabs type="border-card" @tab-click="tabChange" v-model="tabValue">
        <el-tab-pane label="未配送配镜单" name="tab1">
          <el-button-group style="margin-bottom: 10px;">
            <el-button type="primary" icon="el-icon-search" @click="searchHandle">查找</el-button>
            <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
            <el-button type="primary" @click="shopSend" :loading="isSend">加工配送</el-button>

            <el-link  style="margin-left:15px;" :href="printUrl" target="_blank" type="info">
              <el-button type="info" @click="getPrintParams">打印单据(品牌)</el-button>
            </el-link>
          </el-button-group>
          <el-form inline label-width="100px" @keyup.enter.native="searchHandle">
            <el-form-item label="配镜单号">
              <el-input v-model="dataForm.saleBillId" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="取镜门店" v-if="this.userInfo.deptType =='2'">
              <el-select v-model="dataForm.takeMirroDeptId" @change="takeMirroDeptIdChange">
                <el-option v-for="item in DeliveryDeptListOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="取镜门店" v-if="this.userInfo.deptType !='2'" >
              <el-select v-model="dataForm.takeMirroDeptId" @change="takeMirroDeptIdChange"  :disabled="this.userInfo.deptType !='2'">
                <el-option v-for="item in deptOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="avue-crud">
            <div class="avue-crud">
              <el-table :data="firstList" border v-loading="dataListLoading" :max-height="tableHeight1" @selection-change="selectionChangeHandle">
                <el-table-column type="selection" width="40"></el-table-column>
                <el-table-column prop="saleBillId" label="配镜单号">
                  <template slot-scope="scope">
                    <el-button type="text" @click="checkDetailByOrder(scope.row.saleBillId)">{{scope.row.saleBillId}}</el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="customerName" label="顾客姓名"></el-table-column>
                <el-table-column prop="takeMirroDeptName" label="取镜门店"></el-table-column>
                <el-table-column prop="takeMirroTime" label="取镜时间"></el-table-column>
                <el-table-column prop="saleType" label="配镜类型">
                  <template slot-scope="scope">
                    <!-- 1-隐形订做,2-框镜订做,3-隐形成品,4-框镜成品,5-辅料-->
                    {{getSaleType(scope.row.saleType)}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="avue-crud__pagination">
              <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
                :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next">
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="已配送配镜单" name="tab2">
          <el-button-group style="margin-bottom: 10px;">
            <el-button type="primary" icon="el-icon-search" @click="searchHandle">查找</el-button>
            <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
          </el-button-group>
          <el-form inline label-width="100px" @keyup.enter.native="searchHandle">
            <el-form-item label="配送单号">
              <el-input v-model="dataForm.deliverBillId" placeholder="配送单号"></el-input>
            </el-form-item>
            <el-form-item label="配送人">
              <el-input v-model="dataForm.workNumber" placeholder="配送人工号"></el-input>
            </el-form-item>
            <el-form-item label="配送门店">
              <el-select v-model="dataForm.takeMirroDeptId" @change="takeMirroDeptIdChange">
                <el-option v-for="item in deptOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="avue-crud">
            <el-table :data="secondList" border v-loading="dataListLoading" :max-height="tableHeight2">
              <el-table-column prop="deliverBillId" label="配送单号"></el-table-column>
              <el-table-column prop="deptName" label="取镜门店"> </el-table-column>
              <el-table-column prop="deliveryTime" label="配送时间"> </el-table-column>
              <el-table-column prop="userName" label="配送人"> </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-edit" @click="getInfoHandle(scope.row.id)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="avue-crud__pagination">
            <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next">
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-dialog title="加工配送" :visible.sync="dialogShow" width="30%">
        <el-button class="miui-dialog-close-btn" @click="dialogShow = false">关闭页面</el-button>
        <el-form ref="dataForm" :model="dataForm" :rules="dataRule">
          <el-form-item label="配送人员">
            <el-select v-model="dataForm.userId" filterable default-first-option @change="userNameChange($event)">
              <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="shopSendOrder" :loading="ischeck" v-prevent-re-click>确 定</el-button>
        </span>
      </el-dialog>

      <detail-dialog v-if="detailDialogVisible" ref="detailDialog"></detail-dialog>
      <order-info v-if="infoVisible" ref="infoDialog"></order-info>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { filterParams } from '@/util/tools'
  import { remote } from '@/api/admin/dict'
  import { getUserListNoRole, getUserListByMenu } from '@/api/admin/user'
  import { getDeptInfo,getObj,getDeptListByUnitId } from '@/api/admin/dept'
  import {
    getWorkUnDeliverySaleByPage,
    getDeliveryByPage,
    addWorkingDelivery,
    getNeedDeliveryDeptList
  } from '@/api/eims/optician/delivery'

  import DetailDialog from './form'
  import OrderInfo from '@/views/eims/optician/glassesinfo/detail'

  export default {
    data() {
      return {
				ischeck: false,
        isSend: false,
        dialogShow: false,
        printUrl: '',
        tabValue: 'tab1',
        dataForm: {
          userId: '',
          saleIdList: [],
          deliveryType: "3",
          deptId: '',
          takeMirroDeptId: '',
          userName: '',
          deptName: '',
          saleBillId: ''
        },
        firstList: [],
        secondList: [],
        saleTypeData: [],
        pageIndex: 1,
        pageSize: 100,
        totalPage: 0,
        dataListLoading: false,
        selectionList: [],
        userOptions: [],
        DeliveryDeptListOptions: [],
        deptOptions: [],
        detailDialogVisible: false, // 查看信息
        dataRule: {
          userId: [{ required: true, message: '配送人不能为空' }]
        },
        infoVisible: false
      }
    },
    components: {
      DetailDialog,
      OrderInfo
    },
    created() {
      remote('sale_type').then(result => {
        this.saleTypeData = result.data.data
      })
      this.isFlag()
      this.getTakeMirroDeptList()
      this.getDeptList()
    },
    computed: {
      ...mapGetters(['permissions', 'userInfo', 'bizData']),
      tableHeight1: function(){
        return window.innerHeight - 260
      },
      tableHeight2: function(){
        return window.innerHeight - 260
      },
    },
    methods: {
      //  查询数据
      searchHandle() {
        this.pageIndex = 1
        this.getDataList()
      },
        //已配送
      searchHandle() {
          this.pageIndex = 1
          this.getDataList()
      },
      tabChange(data) {
        for(let key in this.dataForm){
          this.dataForm[key] = ''
          if(key == 'saleIdList'){
            this.dataForm[key] = []
          }
        }
        this.firstList = []
        this.secondList = []
        this.pageIndex = 1
        this.getDataList()
      },
      // 取镜部门change事件
      takeMirroDeptIdChange(val) {
        this.getDataList()
      },
      //  根据key值获取url
      getPathByKey(key) {
        let obj = {}
        obj = this.bizData.personTypeData.find(item => {
          if (item.key == key) {
            return item
          }
        })
        if (obj) {
          return obj.value
        }
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        if(this.tabValue == 'tab1'){
          this.getUserList()
          let params1 = { current: this.pageIndex, size: this.pageSize }
          let params2 = filterParams(this.dataForm)
          getWorkUnDeliverySaleByPage(Object.assign(params1, params2)).then(response => {
            if(response.data.code == '0'){
              this.firstList = response.data.data.records
              this.totalPage = response.data.data.total
            }else{
              this.$message.error(response.data.msg)
            }
            this.dataListLoading = false
          })
        }else if(this.tabValue == 'tab2'){
          //  配送类型---1、门店配送  2、隐形订做配送  3、加工配送
          let params1 = { current: this.pageIndex, size: this.pageSize, deliveryType: '3' }
          let params2 = filterParams(this.dataForm)
          getDeliveryByPage(Object.assign(params1,params2)).then(response => {
            if(response.data.code == '0'){
              this.secondList = response.data.data.records
              this.totalPage = response.data.data.total
            }else{
              this.$message.error(response.data.msg)
            }
            this.dataListLoading = false
          })
        }

      },
      getDeptList() {
          getDeptInfo().then(response => {
            if(response.data.code == '0'){
              this.deptOptions = response.data.data
            }else{
              this.$message.error(response.data.msg)
            }
              //this.searchHandle()
          })
      },
      //判断是否为总库的加工中心
      isFlag(){
        if(this.userInfo.deptType != '2'){
            let saleDept =[];
            getDeptListByUnitId(this.userInfo.unitId).then(response =>{
              if(response.data.code == '0'){
                this.saleDept = response.data.data
                this.dataForm.takeMirroDeptId = this.saleDept[0].id
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
      },
      // 每页数据条数变化事件
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页改变事件
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      //  查看配镜单详情
      checkDetailByOrder(order) {
        this.infoVisible = true;
        this.$nextTick(() => {
          this.$refs.infoDialog.init('', order, '配镜单详情');
        });
      },
      // 查看
      getInfoHandle(id) {
        this.detailDialogVisible = true
        this.$nextTick(() => {
          this.$refs.detailDialog.init(id)
        })
      },
      //获取配镜类型枚举
      getSaleType: function(value) {
        let obj = {};
        obj = this.saleTypeData.find((item) => {
          return item.value == value;
        });
        if(obj && obj.label){
          return obj.label
        }
      },
      // 搜索清空
      searchReset() {
        this.dataForm = {};
      },
      handleSearchShow() {
        this.searchShow = !this.searchShow;
      },
      // 多选表格change事件
      selectionChangeHandle(val) {
        this.selectionList = val
      },

      // 获取员工用户列表
      getUserList(id) {
        let path = this.getPathByKey('3')
        getUserListByMenu({
          menuUrl: path
        }).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let userList = []
            resultData.forEach(item => {
              let userObj = {
                value: item.id,
                label: item.realName + '-' + item.workNumber
              }
              userList.push(userObj)
            })
            this.userOptions = userList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      userNameChange($event) {
        this.userOptions.forEach(item => {
          if (item.value == $event) {
            this.dataForm.userName = item.label.split('-')[0]
          }
        })
      },
      //弹框
      shopSend() {
        this.isSend = true
        if (this.selectionList.length) {
          this.dialogShow = true
        } else {
          this.isSend = false
          this.$message.warning('请选择配镜单')
        }
      },
      //点击门店配送接口
      shopSendOrder() {
        this.dataForm.saleIdList = [];
        let ids = []
        this.selectionList.forEach((item, index) => {
          if (index == 0) {
            this.dataForm.deptId = item.takeMirroDeptId
          }
          ids.push(item.saleId)
        })
        this.dataForm.saleIdList = ids;
        if (this.dataForm.takeMirroDeptId) {
          this.dataForm.deptId = this.dataForm.takeMirroDeptId;
        }
				this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addWorkingDelivery(this.dataForm).then(response => {
              if(response.data.code == '0'){
                this.$message.success("配送成功")
                this.dialogShow = false
                this.getDataList()
              }else{
                this.$message.error(response.data.msg)
              }
              this.isSend = false
              this.ischeck = false
            }).catch(() => {
              this.isSend = false
							this.ischeck = false
						})
          }else{
            this.isSend = false
						this.ischeck = false
					}
        })
      },
      // 获取取镜门店列表
      getTakeMirroDeptList() {
        getNeedDeliveryDeptList({
          deliveryType: '3'
        }).then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let list = []
            resultData.forEach(item => {
              list.push({
                value: item.id,
                label: item.name
              })
            })
            this.DeliveryDeptListOptions = list
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //  打印单据
      getPrintParams() {
        let params = '/deliveryInfo.cpt&ids='
        let ids = []
        this.selectionList.forEach(item => {
          ids.push(item.saleId)
        })
        this.printUrl = this.bizData.printUrl + params + ids
      }
    }
  }
</script>
